package com.zhongwei.lvzhixuanmanage.handle;

import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhongwei.lvzhixuanmanage.annotation.ResponseResult;
import com.zhongwei.lvzhixuanmanage.vo.ResultCode;
import com.zhongwei.lvzhixuanmanage.utils.ResultMsgUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 判断请求request中是否包含标记RESPONSE_RESULT_ANN，有则重写返回体
 */
@ControllerAdvice
public class ResponseHandle implements ResponseBodyAdvice<Object> {
    //标记名称
    public static final String RESPONSE_RESULT_ANN = "RESPONSE_RESULT_ANN";

    //请求是否包含了包装注解 标记 没有就直接返回 不需要重写返回体
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //判断请求是否包装标记
        ResponseResult responseResultHead = (ResponseResult) sra.getRequest().getAttribute(RESPONSE_RESULT_ANN);
        return responseResultHead != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //重写返回体
        System.out.println("========"+body);
        if (body == null){
            return ResultMsgUtils.failure(ResultCode.EMPTY).getResultJson();
        } else if(body.equals(false)){
            return ResultMsgUtils.failure(ResultCode.OPERATION_FAIL).getResultJson();
        } else if(body instanceof ResultMsgUtils ){
            return ((ResultMsgUtils) body).getResultJson();
        } else if (body instanceof String){
            ObjectMapper om = new ObjectMapper();
            try {
                return om.writeValueAsString(ResultMsgUtils.success(body).getResultJson());
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        } else if(body instanceof JSONObject){
            return body;
        }
        return ResultMsgUtils.success(body).getResultJson();
    }
}
